package org.example.nio_demo;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

/**
 * @ClassName Demo6
 * @Description
 * @Author zhangsw
 * @Date 2020/11/11 22:45
 * @Version 1.0
 */
public class Demo6 {
    public static void main(String[] args) throws CharacterCodingException {
        /*NIO支持的字符集*/
        SortedMap<String, Charset> sortedMap = Charset.availableCharsets();
        for (Map.Entry<String, Charset> entries : sortedMap.entrySet()) {
            System.err.println(entries);
        }

        System.out.println("-------------------------------------------");

        Charset gbk = Charset.forName("GBK");
        //获取编码器
        CharsetEncoder encoder = gbk.newEncoder();
        //获取解码器
        CharsetDecoder decoder = gbk.newDecoder();

        CharBuffer buffer = CharBuffer.allocate(1024);
        buffer.put("张三丰");
        buffer.flip();

        //编码
        ByteBuffer encode = encoder.encode(buffer);
        for (int i = 0; i < 6; i++) {
            System.err.println(encode.get());
        }

        //解码
        encode.flip();
        CharBuffer decode = decoder.decode(encode);
        System.err.println(decode.toString());

        System.err.println("====================================");

        Charset utf8 = Charset.forName("UTF-8");
        encode.flip();
        CharBuffer de = utf8.decode(encode);
        System.err.println(de.toString());//乱码 ������
    }
}
